/*
 * @Descripttion: 
 * @version: 
 * @Author: jwZhang
 * @Date: 2020-04-30 20:44:32
 * @LastEditors: jwZhang
 * @LastEditTime: 2020-05-10 16:44:13
 */
import 'package:cloud_music/application.dart';
import 'package:cloud_music/core/datamodels/user.dart';
import 'package:cloud_music/core/services/user/user_request.dart';
import 'package:cloud_music/utils/utils.dart';
import 'package:flutter/material.dart';
import 'dart:convert';

class UserModel with ChangeNotifier {
  User _user;

  User get user => _user;

  // 初始化
  void initUser() {
    //  如果本地缓存有用户信息 从缓存加载
    if (Application.sp.containsKey('user')) {
      String s = Application.sp.getString('user');
      _user = User.fromJson(json.decode(s));
    }
  }

  // 登录
  Future<User> login(
      BuildContext context, String account, String password) async {
    // 判断是什么类型登录/用户名/密码/邮箱,或者由后台判断
    User user = await UserRequest.login(context, account, password, 1);
    if (user.code > 299) {
      Utils.showToast(user.msg ?? '登录成功');
      _saveUserInfo(user);
      return user;
    }
  }

  // 保存用户信息到缓存
  _saveUserInfo(user) {
    _user = user;
    Application.sp.setString('user', json.encode(user.toJson()));
  }
}
